﻿using System;
using System.Windows.Forms;
using GogTasks.Entities;
using System.Threading;

namespace GogTasks.UserControls
{
    public class ImageButton : PictureBox, System.ComponentModel.ISupportInitialize
    {
        private ThreeStateIcon _icon;
        public ThreeStateIcon Icon { 
            get { return _icon; } 
            set { _icon = value;
                SetPicture();
            }
        }

            /// <summary>
        /// Timed blink instead of mouseUp resetting image to default
        /// </summary>
        public bool BlinkOnClick { get; set; }

        public new bool Enabled { 
            get { return base.Enabled; }
            set 
            { 
                base.Enabled = value;
                SetPicture();
            }
        }

        private bool _inited;
        private bool _hightlighted;

        public ImageButton()
        {
            MouseDown += new MouseEventHandler(ImageButton_MouseDown);
            MouseUp += new MouseEventHandler(ImageButton_MouseUp);
        }

        void ImageButton_MouseUp(object sender, MouseEventArgs e)
        {
            if (BlinkOnClick) return;
            _hightlighted = false; 
            SetPicture();
        }

        void ImageButton_MouseDown(object sender, MouseEventArgs e)
        {
            _hightlighted = true;
            SetPicture();
            if (BlinkOnClick) StartBlink();
        }

        private void StartBlink()
        {
            var t = new Thread(Blink);
            t.Start();
        }

        private void Blink()
        {
            Thread.Sleep(300);
            _hightlighted = false;
            Invoke(new MethodInvoker(SetPicture));
        }

        private delegate void MethodInvoker();

        public ImageButton(ThreeStateIcon icon) : this()
        {
            Icon = icon;
        }

        private void Init()
        {
            SetPicture();
            _inited = true;
        }

        private void SetPicture()
        {
            if (_hightlighted) Image = Icon.Highlighted;
            else if (!Enabled) Image = Icon.Disabled;
            else Image = Icon.Standard;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (!_inited) Init();
            base.OnPaint(e);
        }


        #region ISupportInitialize Members

        public void BeginInit()
        { 
        }

        public void EndInit()
        { 
        }

        #endregion
    }
}
